package main

import (
	"crypto/tls"
	"fmt"
	"github.com/gorilla/websocket"
	"log"
	"net/url"
	"os"
	"os/signal"
	"time"
)

func main() {
	TestWebSocketClient("127.0.0.1:8111", false)
}
func TestWebSocketClient(addr string, isWss bool) {
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)

	ws := "ws"
	if isWss {
		ws = "wss"
	}
	u := url.URL{Scheme: ws, Host: addr, Path: "/ws"} // WebSocket服务器的地址

	// 创建一个自定义的 TLS 配置，允许自签名证书
	dialer := websocket.DefaultDialer
	if isWss {
		dialer.TLSClientConfig = &tls.Config{
			InsecureSkipVerify: true, // 忽略证书验证
		}
	}

	c, _, err := dialer.Dial(u.String(), nil)
	if err != nil {
		log.Fatal("dial:", err)
	}
	defer c.Close()

	done := make(chan struct{})

	// 启动接收消息的协程
	go func() {
		defer close(done)
		for {
			_, message, err := c.ReadMessage()
			if err != nil {
				log.Println("read:", err)
				return
			}
			fmt.Printf("Received message: %s\n", message)
		}
	}()

	// 启动发送消息的协程
	go func() {
		for {
			select {
			case <-done:
				return
			default:

				data := []byte{
					0x48, 0x65, 0x6c, 0x6c, 0x6f, //输出: 48656c6c6f
					0x11, 0x11, 0x11, 0x11, 0x11,
					0x11, 0x11, 0x11, 0x11, 0x11,
				}
				err := c.WriteMessage(websocket.BinaryMessage, data /*[]byte("Hello, WebSocket Server!")*/)
				if err != nil {
					log.Println("write:", err)
					return
				}
				time.Sleep(time.Second)
			}
		}
	}()

	log.Println("WebSocket client connected")

	// 等待中断信号
	<-interrupt
	log.Println("Interrupt signal received")

	// 关闭连接
	err = c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
	if err != nil {
		log.Println("write close:", err)
		return
	}

	select {
	case <-done:
	case <-time.After(time.Second):
		log.Println("timeout waiting for server to close connection")
	}
}
